#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
# @Time    : 2021/5/8 4:24 下午
# @Author  : 姜晖
# @Email   : jianghui@tianyancha.com
# @File    : utils.py
import string

import yaml
import redis
from random import Random
import random


def load_env():
    env = yaml.safe_load(open('../../env.yml'))
    return env


def load_datafile(filePath, parm=None, env = load_env()["default"]):
    '''
    @param filePath: 文件路径
    @param parm: 测试数据配置文件二级参数
    @return: 返回测试数据，para不填返回配置文件中的二级参数
    '''
    data = yaml.safe_load(open(filePath))

    return [i for i in data[env]] if parm is None else data[env][parm]


# 连接redis
def connect_redis(key_type, dbindex=8, phone=None):
    """
    :param key_type: redis不同类型验证码的key
    :param dbindex: redis表
    :param phone: 接收验证码的手机号
    :return:
    """
    if load_env()['default'] == 'test':
        pool = redis.ConnectionPool(host='10.2.16.44', port=6379, db=dbindex, decode_responses=True)
        r = redis.Redis(connection_pool=pool)
        return r.get('{}{}'.format(key_type, phone))

    elif load_env()['default'] == 'pre':
        pool = redis.ConnectionPool(host='r-2zexsl61h0zcfcrhaq.redis.rds.aliyuncs.com', password='J1ndiTianyanyufa',
                        port=6379, db=dbindex, decode_responses=True)
        r = redis.Redis(connection_pool=pool)
        return r.get('{}{}'.format(key_type, phone))

    # 线上redis地址
    else:
        pass


def sms_redis(key,account):
    if load_env()['default'] == 'test':
        pool = redis.ConnectionPool(host='10.2.16.44', port=6379, db=8, decode_responses=True)
        r = redis.Redis(connection_pool=pool)
        # time.sleep(2)
        value_test = r.get(key + account)
        # print("测试环境验证码为：", value_test)
        return value_test  # 用户侧账号注册获取验证码key
    elif load_env()['default'] == 'pre':
        pool = redis.ConnectionPool(host= 'r-2zexsl61h0zcfcrhaq.redis.rds.aliyuncs.com',password= "J1ndiTianyanyufa", port=6379, db=8,  decode_responses=True)
        r = redis.Redis(connection_pool=pool)
        try:
            value_pre = r.get(key + account) # 用户侧账号注册获取验证码key
            # print("验证码是",value)
            return value_pre
        except:
            print("未找到对应key-value")


def generate_strings(random_length):
    """
    随机生成固定长度的字符串
    """
    s = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(random_length):
        s += chars[random.randint(0, length)]
    return s


def generate_random_str(random_length=50):
    str_list = [random.choice(string.digits + string.ascii_letters) for i in range(random_length)]
    random_str = ''.join(str_list)
    return random_str
